package com.wechatapp.mengyao.poetry.interceptor;

import com.wechatapp.mengyao.poetry.core.CurrentContext;
import com.wechatapp.mengyao.poetry.core.JwtUtils;
import com.wechatapp.mengyao.poetry.entity.UserInfo;
import com.wechatapp.mengyao.poetry.exception.InvalidTokenException;
import com.wechatapp.mengyao.poetry.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yanghuaxu
 * @date 2025/5/21 8:55
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 获取Token
        String token = request.getHeader(JwtUtils.AUTH_TOKEN_HEADER);
        if (token == null || !token.startsWith("Bearer ")) {
            throw new InvalidTokenException("auth token 格式错误");
        }
        String platform = request.getHeader(JwtUtils.AUTH_PLATFORM);
        if (!StringUtils.hasText(platform)) {
            platform = UserInfo.Platform.WX.name();
        }
        userInfoService.parseToken(token, platform);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentContext.destroy();
    }
}
